<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.orderNumber ? '新增' : '查看'"
    :close-on-click-modal="false"
    width="80%"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-width="120px"
      @keyup.enter="onSubmit()"
    >
      <div class="main">
        <div class="content">
          <div class="order-number">
            <div class="num-cont">
              <el-form-item label="订单编号:">
                <span class="text">{{ dataForm.orderNumber }}</span>
              </el-form-item>
              <el-form-item>
                <el-steps
                  :active="stepsStatus"
                  align-center
                  :process-status="dataForm.status == 6 ? 'error' : 'wait'"
                >
                  <el-step title="提交订单" :description="dataForm.orderTime" />
                  <el-step title="买家已付款" :description="dataForm.payTime" />
                  <el-step
                    v-if="dataForm.orderType !== 1"
                    title="检测完成"
                    :description="dataForm.dvyTime"
                  />
                  <el-step
                    v-if="dataForm.orderType !== 1"
                    title="买家已确认"
                    :description="dataForm.finallyTime"
                  />
                </el-steps>
              </el-form-item>
            </div>
          </div>
          <div class="order-state">
            <div class="state-cont">
              <div class="state-title">
                <el-form-item label="订单状态:">
                  <template #default>
                    <el-tag v-if="dataForm.status === 1" type="warning">
                      待付款
                    </el-tag>
                    <el-tag
                      v-if="dataForm.status === 2 && dataForm.orderType !== 1"
                      type="warning"
                    >
                      待检测
                    </el-tag>
                    <el-tag
                      v-if="dataForm.status === 3 && dataForm.orderType !== 1"
                      type="warning"
                    >
                      待确认结果
                    </el-tag>
                    <el-tag
                      v-if="dataForm.status === 4 && dataForm.orderType !== 1"
                      type="warning"
                    >
                      待评价
                    </el-tag>
                    <el-tag v-if="dataForm.status === 5" type="success">
                      已完成
                    </el-tag>
                    <el-tag v-if="dataForm.status === 6" type="danger">
                      失败
                    </el-tag>
                    <el-tag v-if="dataForm.status === 7">检测中</el-tag>
                    <el-tag v-if="dataForm.status === 8">已取消</el-tag>
                    <el-tag v-if="dataForm.status === 9">待改价</el-tag>
                    <el-tag v-if="dataForm.status === 10"
                      >改价完成待支付</el-tag
                    >
                  </template>
                </el-form-item>
                <el-form-item>
                  <el-row>
                    <el-button
                      v-if="dataForm.status === 7"
                      type="primary"
                      plain
                      @click="changeOrder(dataForm.orderNumber)"
                    >
                      检测完成
                    </el-button>
                    <el-button
                      v-if="dataForm.status === 2"
                      type="primary"
                      plain
                      @click="startDetection(dataForm.orderNumber)"
                    >
                      开始检测
                    </el-button>
                    <el-button
                      v-if="dataForm.status === 9"
                      type="primary"
                      plain
                      @click="changePrice(dataForm.orderNumber)"
                    >
                      改价
                    </el-button>
                  </el-row>
                </el-form-item>
              </div>
              <div class="order-info">
                <div class="order-details">
                  <div class="detail-title">
                    <img src="~@/assets/img/car.png" alt="" />
                    <span class="prompt">买家付款后才可以检测</span>
                  </div>
                  <div class="detail-cont">
                    <div class="detail01">
                      <img src="~@/assets/img/address.png" alt="" />
                      <div class="text-width">
                        <div class="info-item">
                          <span class="info-label">收货人:</span>
                          <span class="info-content">{{
                            dataForm.userAddrOrder.receiver
                          }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">手机:</span>
                          <span class="info-content">{{
                            dataForm.userAddrOrder.mobile
                          }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">收货地址:</span>
                          <span class="info-content">
                            {{ dataForm.userAddrOrder.province
                            }}{{ dataForm.userAddrOrder.city
                            }}{{ dataForm.userAddrOrder.area
                            }}{{ dataForm.userAddrOrder.addr }}
                          </span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">样品名称:</span>
                          <span class="info-content">{{
                            dataForm.sampleName
                          }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">样品编号:</span>
                          <span class="info-content">{{
                            dataForm.sampleNo
                          }}</span>
                        </div>

                        <div
                          class="info-item"
                          v-for="orderItem in dataList"
                          :key="orderItem.name"
                        >
                          <span class="info-label">{{ orderItem.name }}:</span>
                          <span
                            class="info-content item-txt"
                            v-if="
                              orderItem.infoFrom == 'in' &&
                              orderItem.choseType == 'input'
                            "
                          >
                            {{ orderItem.value }}
                          </span>

                          <span
                            class="info-content item-txt"
                            v-else-if="
                              orderItem.infoFrom == 'in' &&
                              (orderItem.choseType == 'checkbox' ||
                                orderItem.choseType == 'single' ||
                                orderItem.choseType == 'elements')
                            "
                          >
                            {{ getCheckboxValue(orderItem.value) }}
                          </span>
                          <span
                            class="info-content item-txt"
                            v-else-if="
                              orderItem.infoFrom == 'out' ||
                              orderItem.infoFrom == 'etchingDepth'
                            "
                          >
                            {{ orderItem.value }}
                          </span>
                          <span
                            class="info-content item-txt"
                            v-else-if="
                              orderItem.infoFrom == 'out' ||
                              orderItem.infoFrom == 'etchingDepth'
                            "
                          >
                            {{ orderItem.value }}
                          </span>
                          <span
                            class="info-content item-txt"
                            v-else-if="
                              orderItem.infoFrom == 'joinTimes' ||
                              orderItem.infoFrom == 'roiTimes'
                            "
                          >
                            {{ orderItem.value }}次
                          </span>
                          <span
                            class="info-content item-txt"
                            v-else-if="
                              orderItem.infoFrom == 'testTime' ||
                              orderItem.infoFrom == 'SEMTsetTime'
                            "
                          >
                            {{ orderItem.value }}分钟
                          </span>
                          <span
                            class="info-content item-txt"
                            v-else-if="orderItem.infoFrom == 'needReturn'"
                          >
                            {{ orderItem.value ? "是" : "否" }}
                          </span>
                          <span
                            class="info-content item-txt"
                            v-else-if="orderItem.infoFrom == 'needCloudVideo'"
                          >
                            {{
                              orderItem.value == 0
                                ? "否"
                                : "是；" +
                                  "云视频时长：" +
                                  orderItem.value +
                                  "分钟"
                            }}
                          </span>
                        </div>
                        <div class="info-item" v-if="dataForm.detectionResult">
                          <span class="info-label">检测结果:</span>
                          <span class="info-content">
                            <a
                              :href="fileUrl"
                              target="_blank"
                              v-for="(
                                fileUrl, index
                              ) in dataForm.detectionResult.split(',')"
                              :key="index"
                            >
                              检测结果文件{{ index + 1 }}
                            </a>
                          </span>
                        </div>
                      </div>
                    </div>
                    <div class="detail01">
                      <img src="~@/assets/img/invoice.png" alt="" />
                      <span>不开发票</span>
                    </div>
                  </div>
                </div>
                <div class="buyers">
                  <div class="detail-title">
                    <img
                      src="~@/assets/img/buyer.png"
                      alt=""
                      style="margin-right: 15px"
                    />
                    <el-form-item
                      label="买家:"
                      style="margin-top: 22px"
                      label-width="60px"
                    >
                      <span>{{ dataForm.nickName }}</span>
                    </el-form-item>
                  </div>
                  <div class="buyers-info">
                    <div class="detail02">
                      <img src="~@/assets/img/message.png" alt="" />
                      <div class="text-width">
                        <span>买家备注:</span>
                        <br />
                        <span>{{ dataForm.remarks }}</span>
                      </div>
                    </div>
                    <div class="detail02" v-if="dataForm.contactPhone">
                      <img src="~@/assets/img/message.png" alt="" />
                      <div class="text-width">
                        <span>买家联系电话:</span>
                        <br />
                        <span>{{ dataForm.contactPhone }}</span>
                      </div>
                    </div>
                    <div class="detail02" v-if="dataForm.extraFile">
                      <img src="~@/assets/img/message.png" alt="" />
                      <div class="text-width">
                        <span>附件:</span>
                        <br />
                        <div
                          v-for="(file, index) in dataForm.extraFile.split(',')"
                          :key="index"
                          style="margin: 5px 0"
                        >
                          <a
                            :href="resourcesUrl + file"
                            target="_blank"
                            style="
                              color: #409eff;
                              text-decoration: none;
                              margin-right: 10px;
                            "
                          >
                            文件{{ index + 1 }}
                          </a>
                          <el-button
                            size="small"
                            type="text"
                            @click="copyFileLink(resourcesUrl + file)"
                            style="padding: 0; font-size: 12px"
                          >
                            复制链接
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="item-list">
                <el-table :data="dataForm.orderItems" border>
                  <el-table-column prop="" label="检测项目">
                    <template #default="scope">
                      <div class="prod-con">
                        <img
                          :src="resourcesUrl + scope.row.pic"
                          class="prod-img"
                        />
                        <span>{{ scope.row.prodName }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="price"
                    label="单价"
                    width="180"
                    align="center"
                  >
                    <template #default="scope">
                      <span>{{ scope.row.price }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="count"
                    label="数量"
                    width="180"
                    align="center"
                  >
                    <template #default="scope">
                      <span>{{ scope.row.prodCount }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="totalPrice"
                    label="总价"
                    width="180"
                    align="center"
                  >
                    <template #default="scope">
                      <span>{{ scope.row.productTotalAmount }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="item-info">
                <el-form-item label="商品总价:">
                  <span class="text">￥{{ dataForm.total }}</span>
                </el-form-item>
                <!-- <el-form-item v-if="dataForm.freightAmount" label="配送费用:">
                  <span class="text">￥{{ dataForm.freightAmount }}</span>
                </el-form-item> -->
                <el-form-item label="应付金额:">
                  <span class="text">￥{{ dataForm.actualTotal }}</span>
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="order-log">
            <div class="log-title">
              <span>订单日志</span>
            </div>
            <div class="log-cont">
              <el-form-item v-if="dataForm.orderTime" label-width="10px">
                <span
                  >{{ dataForm.orderTime }}
                  {{ dataForm.nickName }} 创建订单（成功）</span
                >
              </el-form-item>
              <el-form-item v-if="dataForm.updateTime" label-width="10px">
                <span
                  >{{ dataForm.updateTime }}
                  {{ dataForm.nickName }} 订单更新（成功）</span
                >
              </el-form-item>
              <el-form-item v-if="dataForm.payTime" label-width="10px">
                <span
                  >{{ dataForm.payTime }}
                  {{ dataForm.nickName }} 订单付款（成功）</span
                >
              </el-form-item>
              <el-form-item v-if="dataForm.dvyTime" label-width="10px">
                <span
                  >{{ dataForm.dvyTime }}
                  {{ dataForm.nickName }} 订单检测完成</span
                >
              </el-form-item>
              <el-form-item v-if="dataForm.finallyTime" label-width="10px">
                <span
                  >{{ dataForm.finallyTime }}
                  {{ dataForm.nickName }} 完成订单（成功）</span
                >
              </el-form-item>
              <el-form-item v-if="dataForm.cancelTime" label-width="10px">
                <span
                  >{{ dataForm.cancelTime }}
                  {{ dataForm.nickName }} 取消订单（成功）</span
                >
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
    </el-form>

    <!-- 弹窗, 新增 / 修改 -->
    <devy-add
      v-if="devyVisible"
      ref="devyAddRef"
      @refresh-data-list="getDataList"
    />
  </el-dialog>
</template>

<script setup>
import DevyAdd from "./order-devy.vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 复制文件链接的方法
const copyFileLink = (fileUrl) => {
  if (navigator.clipboard) {
    navigator.clipboard
      .writeText(fileUrl)
      .then(() => {
        ElMessage.success("文件链接已复制到剪贴板");
      })
      .catch(() => {
        // 降级方案
        fallbackCopyTextToClipboard(fileUrl);
      });
  } else {
    // 降级方案
    fallbackCopyTextToClipboard(fileUrl);
  }
};

// 降级复制方案
const fallbackCopyTextToClipboard = (text) => {
  const textArea = document.createElement("textarea");
  textArea.value = text;
  textArea.style.position = "fixed";
  textArea.style.left = "-9999px";
  textArea.style.top = "-9999px";
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    const successful = document.execCommand("copy");
    if (successful) {
      ElMessage.success("文件链接已复制到剪贴板");
    } else {
      ElMessage.error("复制失败，请手动复制");
    }
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }

  document.body.removeChild(textArea);
};
const emit = defineEmits(["refresh-data-list"]);
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL;
const dataForm = ref({
  orderId: 0,
  orderNumber: "",
  remarks: "",
  total: 0,
  actualTotal: 0,
  dvyType: "",
  status: 1,
  addrOrderId: 0,
  nickName: "",
  orderItems: [],
  orderTime: "",
  updateTime: "",
  payTime: "",
  dvyTime: "",
  finallyTime: "",
  cancelTime: "",
  userAddrOrder: {},
  detectionResult: "",
});

const stepsStatus = computed(() => {
  if (dataForm.value.finallyTime) {
    return 4;
  }
  if (dataForm.value.dvyTime) {
    return 3;
  }
  if (dataForm.value.payTime) {
    return 2;
  }
  if (dataForm.value.orderTime) {
    return 1;
  }
  return "";
});

const hasNeedReturn = computed(() => {
  return dataList.value.some(
    (item) => item.infoFrom === "needReturn" && item.value === true
  );
});

const visible = ref(false);
const devyVisible = ref(false);
watch(
  () => visible.value,
  () => {
    if (!visible.value) {
      devyVisible.value = false;
    }
  }
);

const dataFormRef = ref(null);
const dataList = ref([]);

const init = (orderNumber) => {
  dataForm.value.orderNumber = orderNumber || 0;
  visible.value = true;
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  if (dataForm.value.orderNumber) {
    // 修改
    http({
      url: http.adornUrl(
        `/order/order/orderInfo/${dataForm.value.orderNumber}`
      ),
      method: "get",
      params: http.adornParams(),
    }).then(({ data }) => {
      console.log(data, "-=--");
      dataForm.value = data;
      dataList.value = JSON.parse(data.orderConfigJson);
      console.log(dataList.value);
    });
  }
};
defineExpose({ init });

const getDataList = () => {
  http({
    url: http.adornUrl(`/order/order/orderInfo/${dataForm.value.orderNumber}`),
    method: "get",
    params: http.adornParams(),
  }).then(({ data }) => {
    dataForm.value = data;
    dataList.value = JSON.parse(data.orderConfigJson);
    console.log(dataList.value);
  });
};

const getCheckboxValue = (value) => {
  let str = "";
  value.forEach((item) => {
    if (item.select == true) {
      str += item.name + " ";
    }
  });
  return str;
};

const devyAddRef = ref(null);
/**
 * 发货
 * @param orderNumber
 */
const changeOrder = (orderNumber) => {
  devyVisible.value = true;
  console.log(dataList.value);
  const needReturn = dataList.value.some(
    (item) => item.infoFrom === "needReturn" && item.value === true
  );
  console.log(needReturn);
  nextTick(() => {
    devyAddRef.value?.init(
      orderNumber,
      dataForm.value.dvyId,
      dataFormRef.value?.dvyFlowId,
      dataForm.value.detectionResult,
      needReturn
    );
  });
};

/**
 * 开始检测
 * @param orderNumber
 */
const startDetection = (orderNumber) => {
  ElMessageBox.confirm("确定要开始检测该订单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      http({
        url: http.adornUrl(`/order/order/detection`),
        method: "put",
        data: http.adornData({
          orderNumber: orderNumber,
        }),
      })
        .then(() => {
          ElMessage.success("开始检测成功");
          getDataList();
          // 触发父组件刷新数据列表
          emit("refresh-data-list");
        })
        .catch(() => {
          ElMessage.error("开始检测失败");
        });
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

/**
 * 改价
 * @param orderNumber
 */
const changePrice = (orderNumber) => {
  ElMessageBox.prompt("请输入改价金额", "改价", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^\d+(\.\d{1,2})?$/,
    inputErrorMessage: "请输入正确的金额格式",
  })
    .then(({ value }) => {
      http({
        url: http.adornUrl(`/order/order/changeTotal`),
        method: "put",
        data: http.adornData({
          orderNumber: orderNumber,
          total: value,
        }),
      })
        .then(() => {
          ElMessage.success("改价成功");
          getDataList();
          // 触发父组件刷新数据列表
          emit("refresh-data-list");
        })
        .catch(() => {
          ElMessage.error("改价失败");
        });
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};
</script>

<style scoped lang="scss">
.main {
  height: 100%;
  width: 100%;
  font: 14px Arial, "PingFang SC", "Hiragino Sans GB", STHeiti,
    "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
  color: #495060;
}
.content {
  margin: 0 20px;
  .order-state {
    position: relative;
    margin-top: 50px;
    border-bottom: 1px solid #e9eaec;
  }
}
.order-number {
  .text {
    font-size: 14px;
    color: #8a8a8a;
  }
}
.order-state {
  .state-title {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .order-info {
    width: 100%;
    border-top: 1px solid #e9eaec;
    margin: 50px 0;
    display: flex;
  }
  .item-info {
    padding-left: 80%;
    margin: 25px 0;
  }
}
.order-info {
  display: flex;
  gap: 24px;
  margin: 30px 0;

  img {
    width: 20px !important;
    height: 20px !important;
    margin-right: 12px;
  }

  .detail-title {
    height: 56px;
    line-height: 56px;
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #1f2d3d;
    border-bottom: 1px solid #f0f2f5;

    .prompt {
      color: #909399;
      font-size: 13px;
      font-weight: normal;
    }
  }

  .order-details {
    flex: 7;
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    border: 1px solid #ebeef5;
  }

  .detail-cont {
    position: relative;
    border-top: 1px dashed #e6e8eb;
    margin: 20px 0 0 0;
    padding-top: 20px;
  }

  .buyers {
    flex: 3;
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    border: 1px solid #ebeef5;
  }
}
.detail-cont {
  .detail01 {
    display: flex;
    height: 100%;
    line-height: 28px;
    margin-top: 16px;
    padding: 12px 0;
    border-radius: 6px;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f8f9fa;
    }

    &:first-child {
      margin-top: 0;
    }
  }
}
.detail01 {
  .text-width {
    width: 100%;

    .info-item {
      display: flex;
      margin-bottom: 12px;
      flex-wrap: wrap;
      align-items: flex-start;

      &:last-child {
        margin-bottom: 0;
      }

      .info-label {
        color: #606266;
        font-weight: 500;
        min-width: 80px;
        flex-shrink: 0;
        margin-right: 12px;
        line-height: 28px;
        word-break: break-word;
        white-space: normal;
      }

      .info-content {
        color: #303133;
        font-size: 14px;
        flex: 1;
        min-width: 0;
        line-height: 28px;
        word-break: break-word;
      }
    }
  }

  .item-txt {
    color: #409eff;
    font-weight: 500;
    word-break: break-word;
  }
}
.detail02 {
  .text-width {
    width: 100%;

    span {
      color: #606266;
      font-size: 14px;
      line-height: 1.6;

      &:first-child {
        color: #303133;
        font-weight: 500;
        margin-bottom: 8px;
        display: inline-block;
      }
    }
  }
}
.buyers {
  .buyers-info {
    border-top: 1px dashed #e6e8eb;
    margin-top: 20px;
    padding-top: 20px;
    position: relative;
  }

  .detail02 {
    display: flex;
    height: 100%;
    line-height: 28px;
    margin-top: 16px;
    padding: 12px 0;
    border-radius: 6px;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f8f9fa;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 0;

    label {
      color: #606266;
      font-weight: 500;
    }

    span {
      color: #303133;
      font-size: 14px;
      font-weight: 500;
    }
  }
}
.item-info {
  span {
    margin-bottom: 15px;
    line-height: 30px;
  }
  .text {
    position: absolute;
    right: 0;
  }
}
.order-log {
  .log-title {
    height: 50px;
    width: 100%;
    line-height: 50px;
    font-weight: bold;
  }
  .log-cont {
    color: #4395ff;
  }
}
.item-list {
  .prod-con {
    display: flex;
    .prod-img {
      width: 100px;
      height: 100px;
      margin-right: 8px;
    }
  }
}
:deep(.el-steps--horizontal) {
  flex: 25% 1 1;
}
</style>
